package com.tuling.limit;

/**
 * 限流的常用方式：
 * 漏桶
 * 摘自： jianshu.com/p/d9504fc0af4d
 *
 * <p>
 * Created by chenhs on 2018/6/28.
 */
public class LeakyBucketDemo {
    //时间刻度
    private static long time = System.currentTimeMillis();
    //桶里面现在的水
    private static int water = 0;
    //桶的大小
    private static int size = 10;
    //出水速率
    private static int rate = 3;

    public static boolean grant() {
        //计算出水的数量
        long now = System.currentTimeMillis();
        int out = (int) ((now - time) * rate / 50);
        System.out.println("out: " + out);
        water = Math.max(0, water - out);
        time = now;
        if ((water + 1) < size) {
            ++water;
            return true;
        } else {
            return false;
        }
    }


    public static void main(String[] args) {
        for (int i = 0; i < 500; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    if (grant()) {
                        System.out.println("执行业务逻辑");
                    } else {
                        System.out.println("限流");
                    }
                }
            }).start();
        }


    /*    int out = (20-5)/10*3;
        int out2 = (20-5)*3/10;
        System.out.println(out);
        System.out.println(out2);*/
    }




}
